<template>
	<view class="page">
		<page-container :overlay="false" :show="isShowPage" @beforeleave="beforeleave"
			custom-style="height:100vh;overflow:scroll">
			<view class="padding-30 box-sizing">
				<view class="flex flex-center items-center">
					<view class="fontSize-28 color-999">
						{{memoryList.top_title}}
					</view>
					<!-- 		<image src="../../static/set-icon.png" mode="" class="marginLeft-24 width-40 height-40"
						@click='toSet'>
					</image> -->
				</view>
				<view class="flex space-between marginTop-32 items-center marginLeft-42">
					<up-line-progress activeColor="#51D580" :showText="false" :percentage="percentage"
						height="8"></up-line-progress>
					<image src="../../static/image/jishi.png" mode=""
						class="width-28 height-28 marginLeft-20 marginRight-6"></image>
					<up-count-down ref="countDown" :time="seconds" format="ss" @change="onChange" @finish="finish">
						<view class="color-51D580 fontSize-28">
							{{ timeData.seconds }}
						</view>
					</up-count-down>

				</view>
				<view class="word-section width-full">
					<view class="word">
						<view class="flex flex-center items-center color-333 fontSize-60 weight-700">
							{{ currentWord.wordHead  }}
						</view>
						<view class="marginTop-20 flex flex-center items-center">
							<image src="../../static/play-icon.png" mode="" class="width-44 height-44"></image>
						</view>
					</view>

				</view>
				<view class="tips flex ">
					<image :src="memoryList.bottom_image" mode="" class="height-80 width-80"></image>
					<view class="color-333 fontSize-28 marginLeft-20" style="width: 90%;">
						{{memoryList.bottom_title}}
					</view>
				</view>
				<view class="flex flex-center items-center marginTop-30">
					<image src="../../static/alarm-icon.png" mode="" class="width-32 height-32"></image>
					<view class="fontSize-24 color-999 marginLeft-10">
						千万别随意选哦
					</view>
				</view>
				<view class="btn-section">
					<view class="btn color-white colorBj-51D580" @click='markAsSeen'>
						见过
					</view>
					<view class="btn color-51D580 colorBj-fff" style="border: 1px solid #51D580;"
						@click='markAsNotSeen'>
						没见过{{notSeenClick}}/10
					</view>
				</view>
			</view>

		</page-container>

		<up-popup :show="backShow" mode='center' bgColor='transparent'>
			<view class="popup_bg" :style="{
		        backgroundImage: `url('${bjImage}')`,
		        backgroundSize: '100% 100%',
				overflow:'hidden',
				padding:'0 40rpx',
				boxSizing:'border-box'
		      }">
				<view class="weight-700 fontSize-52 color-white text-center marginTop-20">
					温馨提示
				</view>
				<view class="fontSize-36 weight-700 color-333  box-sizing text-center" style="margin-top: 100rpx;">
					距领取超级个性化记忆方案只差一步，再坚持一下吧！退出后本次测试记录将被清空
				</view>
				<view class="flex space-between items-center  box-sizing marginTop-50">
					<view class="color-white borderRadius-74 fontSize-32 text-center width-252 height-92"
						style="background-color: #ccc; line-height: 92rpx;" @click='back'>
						使用通用方案
					</view>
					<view
						class="color-white borderRadius-74 fontSize-32 colorBj-51D580  text-center width-252 height-92"
						style="line-height: 92rpx;" @click='continueText'>
						重新测试
					</view>

				</view>
			</view>
		</up-popup>
		<up-popup :show="firstShow" mode='center' bgColor='transparent'>
			<view class="popup_bg" :style="{
		        backgroundImage: `url('${bjImage}')`,
		        backgroundSize: '100% 100%',
				overflow:'hidden',
				padding:'0 40rpx',
				boxSizing:'border-box'
		      }">
				<view class="weight-700 fontSize-52 color-white text-center marginTop-20">
					温馨提示
				</view>
				<view class="fontSize-36 weight-700 color-333  box-sizing text-center" style="margin-top: 100rpx;">
					系统未检测到您的操作，默认该词为"没见过"
				</view>
				<view class="flex flex-center items-center  box-sizing marginTop-50">
					<view
						class="color-white borderRadius-74 fontSize-32 colorBj-51D580  text-center width-252 height-92"
						style="line-height: 92rpx;" @click='btnClick'>
						知道了
					</view>

				</view>
			</view>
		</up-popup>
		<up-popup :show="tipsShow" mode='center' bgColor='transparent'>
			<view class="popup_bg" :style="{
		        backgroundImage: `url('${bjImage}')`,
		        backgroundSize: '100% 100%',
				overflow:'hidden',
				padding:'0 40rpx',
				boxSizing:'border-box'
		      }">
				<view class="weight-700 fontSize-52 color-white text-center marginTop-20">
					温馨提示
				</view>
				<view class="fontSize-36 weight-700 color-333  box-sizing text-center" style="margin-top: 100rpx;">
					由于长时间未检测到您操作，测试终止
				</view>
				<view class="flex flex-center items-center  box-sizing marginTop-50">
					<view class="flex space-between items-center  box-sizing marginTop-50">
						<view class="color-white borderRadius-74 fontSize-32 text-center width-252 height-92"
							style="background-color: #ccc; line-height: 92rpx;" @click='back'>
							使用通用方案
						</view>
						<view
							class="color-white borderRadius-74 fontSize-32 colorBj-51D580  text-center width-252 height-92"
							style="line-height: 92rpx;" @click='continueText'>
							重新测试
						</view>

					</view>

				</view>
			</view>
		</up-popup>


	</view>

</template>

<script setup>
	import {
		inject,
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onLoad,
		onUnload,
		onShow,
	} from '@dcloudio/uni-app'

	const memoryWordsListApi = inject('memoryWordsList')
	const insertNotseenApi = inject('insertNotseen')
	const outMemoryWordMethodApi = inject('outMemoryWordMethod')

	const memoryList = ref({})
	const WordList = ref([])
	const tipsShow = ref(false)
	const firstShow = ref(false)
	const backShow = ref(false)
	const isShowPage = ref(true)
	const bjImage = ref('')
	const firstword = ref('')
	const countdownTime = ref(10);
	const timeData = ref({});
	const seconds = ref(10000)
	const percentage = ref(100)

	const countDown = ref(null);

	const currentWordIndex = ref(0);
	const currentWord = ref(() => WordList.value[currentWordIndex.value]);
	// 于记录未点击按钮的次数
	const noClickCount = ref(0);
	// 定时器的标识
	let timer = null;
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	const notseen_num = ref(0)
	innerAudioContext.onCanplay(() => {
		console.log('可以播放l ');
		// setTimeout(() => { 
		// console.log('开始播放');
		// innerAudioContext.play()
		// }, 1000)
	});
	innerAudioContext.onPlay((e) => {

		console.log('音频播放事件', e);
	})
	innerAudioContext.onEnded((e) => {

		// _this.voiceLoading = false
		console.log('音频自然播放结束事件', e);
	})

	const getWordList = () => {
		memoryWordsListApi().then(res => {
			console.log(res, '66666666666')
			memoryList.value = res
			WordList.value = res.data
			currentWord.value = WordList.value[currentWordIndex.value];
			bjImage.value = res.end_image
			firstword.value = res.data[0].wordHead
		})
	}
	onLoad((op) => {
		getWordList()
		startAutoSwitchTimer();
		innerAudioContext.stop();
		notseen_num.value = op.notseen_num

		setTimeout(() => {
			console.log('firstword.value', firstword.value)
			innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${firstword.value}&type=1`;
			innerAudioContext.play();
		}, 1000);
	})
	const onChange = (e) => {
		timeData.value = e;
		percentage.value = (e.seconds / 10) * 100
	};
	const finish = (e) => {
		console.log(e, '倒计时结束')
	};

	const showNextWord = () => {
		currentWordIndex.value++;
		console.log(currentWordIndex.value)
		// if (currentWordIndex.value <= WordList.value.length) {
		// 	currentWord.value = WordList.value[currentWordIndex.value];
		// 	
		// }
	};


	// 用于记录点击“见过”按钮的次数
	const seenCount = ref(0);

	// 用于记录点击“没见过”按钮的次数
	const notSeenCount = ref(0);
	const notSeenClick = ref(0);


	// 用于存储点击十次后要发送到后端的单词对应的wordId列表
	const wordIdsToSend = ref([]);



	// const word = currentWord.value.wordHead
	const markAsSeen = () => {
		seenCount.value++;

		// 获取当前单词信息

		checkAndCallGetWordList();
		switchToNextWord();
		stopAutoSwitchTimer();
	};

	const markAsNotSeen = () => {
		notSeenCount.value++;
		notSeenClick.value++;
		wordIdsToSend.value.push(currentWord.value.wordId);

		checkAndCallGetWordList();
		switchToNextWord();
		stopAutoSwitchTimer();
	};




	const totalNum = ref(0)
	const checkAndCallGetWordList = async () => {
		totalNum.value = seenCount.value + notSeenCount.value
		while (totalNum.value === 10 && wordIdsToSend.value.length < 10) {
			try {
				totalNum.value = 0;
				seenCount.value = 0
				notSeenCount.value = 0
				await getWordList();
			} catch (error) {
				console.error('执行过程中出错：', error);
			}
		}

		if (wordIdsToSend.value.length === 10) {
			insertNotseenApi({
				notword: wordIdsToSend.value.join(',')
			}).then(res => {
				uni.redirectTo({
					url: '/pages/index/memoryMaxStepOneTotal'
				})
			})

		}
	};




	// 切换到下一个单词的方法
	const switchToNextWord = () => {
		currentWordIndex.value++;
		seconds.value = 10000
		percentage.value = 100
		countDown.value.reset();
		if (currentWordIndex.value >= WordList.value.length) {
			currentWordIndex.value = 0;
		}
		currentWord.value = WordList.value[currentWordIndex.value];
		const currentWordInfo = WordList.value[currentWordIndex.value];
		const word = currentWordInfo.wordHead;
		console.log(word)
		innerAudioContext.stop();
		innerAudioContext.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=1`;
		innerAudioContext.play();
	}
	// 启动定时器函数
	const startAutoSwitchTimer = () => {
		// 记录定时器启动的初始时间
		const startTime = Date.now();
		timer = setInterval(() => {
			const elapsedTime = Date.now() - startTime;
			// 根据经过的时间计算剩余秒数，实现一秒一秒倒计时
			countdownTime.value = Math.max(0, Math.floor((10000 - elapsedTime) / 1000));

			if (countdownTime.value === 0) {
				noClickCount.value++;
				notSeenCount.value++;

				if (noClickCount.value === 1) {
					// 第一次未点击按钮弹出提示框
					clearInterval(timer);
					firstShow.value = true;
				} else if (noClickCount.value === 2) {
					// 连续两次未点击按钮，停止定时器并弹出弹窗
					clearInterval(timer);
					tipsShow.value = true;
				} else {
					// 否则重新启动定时器
					startAutoSwitchTimer();
					switchToNextWord();
				}
			}
		}, 1000);
	};

	// 停止定时器函数
	const stopAutoSwitchTimer = () => {
		clearTimeout(timer);
		noClickCount.value = 0;
	};
	const continueText = () => {
		outMemoryWordMethodApi({
			type: '2'
		}).then(res => {
			uni.redirectTo({
				url: '/pages/index/memoryMax'
			})
		})
	}
	//使用通用方案
	const info = ref({});
	info.value = uni.getStorageSync("userInfo");
	const getMaxmemoryApi = inject('getMaxmemory')
	const back = () => {
		//记单词
		if (Object.keys(info.value).length > 0) {
			getMaxmemory();
		} else {
			uni.navigateTo({
				url: "/pages/login/login",
			});
		}

	}
	//1-跳转刷单词页  2-跳转未记录记忆上限  3-跳转记单词 4-无电话跳转获取电话页
	const getMaxmemory = () => {
		getMaxmemoryApi().then((r) => {
			console.log(r, 319);
			let res = r[0];
			console.log(res, 313)
			if (res.zt == "1") {
				uni.redirectTo({
					url: "/pages/index/brushWords",
				});
			} else if (res.zt == "2") {
				uni.redirectTo({
					url: "/pages/index/memoryMax",
				});
			} else if (res.zt == "3") {
				console.log(res.mobile);
				outMemoryWordMethodApi({
					type: '1'
				}).then(res2 => {
					if (res.mobile && res.mobile.length > 0) {
						uni.redirectTo({
							url: "/pagesA/memory/memoryGuide",
						});
					}
				})

			} else if (res.zt == "4") {
				uni.redirectTo({
					url: "/pages/index/bindPhone",
				});
			}
		});
	};
	//退出页面
	const beforeleave = (e) => {
		isShowPage.value = false
		backShow.value = true
		stopAutoSwitchTimer()
	}

	const btnClick = () => {
		firstShow.value = false
		switchToNextWord();
		startAutoSwitchTimer();
	}
</script>

<style>
	page {
		position: relative !important;
		top: 0px !important;
	}
</style>

<style lang="scss">
	.word-section {
		position: relative;
		height: 50vh;

		.word {
			width: 100%;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			text-align: center;
		}
	}

	.tips {
		padding: 32rpx 50rpx;
		box-shadow: 0rpx 8rpx 30rpx 0rpx rgba(0, 0, 0, 0.1);
		border-radius: 30rpx;
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		padding: 30rpx 0;
		margin-top: 24rpx;
		border-radius: 92rpx;

	}

	.popup_bg {
		width: 610rpx;
		height: 500rpx;
	}
</style>